#include "Bluetooth.h"

BT_struct BT36 = {0};
uint8_t BT36_temp = 0;

void BT_init(BT_struct * bt)
{
    //bt->data = 0;
    bt->data_is_fresh = 0;
    bt->is_connected = 0; // 初始化连接状态
    bt->uart = &bt_uart5; // 设置使用的UART结构体
}


void BT_receive_data(BT_struct * bt, uint8_t data)
{
    //bt->data = data; 
    bt->data_is_fresh = 1;
    
}



void BT_printf(const char *format, ...)
{
    va_list args;
    char buffer[128]; // 假设最大长度为128
    va_start(args, format);
    vsnprintf(buffer, sizeof(buffer), format, args);
    va_end(args);

    // 计算实际字符串长度（不包括\0）
    uint16_t len = strlen(buffer);

    // 启动发送
    HAL_UART_Transmit(&huart5, (uint8_t *)buffer, len, HAL_MAX_DELAY);

}

void BT_proc(void)
{
    BT_struct * bt = &BT36;
    //每次调用proc都检查是否连接成功,主机每次都发送
    if (bt->is_connected == 1 && bt->data_is_fresh)
    {
        bt->data_is_fresh = 0;
        //输出串口接收到的数据
        // 假设 bt->uart->receivedata 存储接收到的数据，bt->uart->receivenum 为长度
        
        if (bt->uart->receivenum == strlen(NOT_CONNECTED_S_STRING) &&
            memcmp(bt->uart->receivedata, NOT_CONNECTED_S_STRING, strlen(NOT_CONNECTED_S_STRING)) == 0)
        {
            bt->is_connected = 0;
        }
        else if (bt->uart->receivenum > 0)
        {
            // 处理接收到的数据
            // 这里可以添加具体的处理逻辑，比如解析命令等
            printf("Received data: %.*s\n", bt->uart->receivenum, bt->uart->receivedata);
        }
    }
    else if (bt->is_connected == 0 && bt->data_is_fresh)
    {
        bt->data_is_fresh = 0;
        // 假设 bt->uart->receivedata 存储接收到的数据，bt->uart->receivenum 为长度
        if (bt->uart->receivenum == strlen(CONNECTED_S_STRING) &&
            memcmp(bt->uart->receivedata, CONNECTED_S_STRING, strlen(CONNECTED_S_STRING)) == 0)
        {
            bt->is_connected = 1;
        }
        
    }
    //BT_printf("nowtick = %d\n", HAL_GetTick()); // 打印当前时间戳
}

